package com.molichuxing.baselibrary.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.molichuxing.baselibrary.R;
import com.molichuxing.baselibrary.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

public class CarBaseView extends View {
    private Bitmap carBitmap;//绘制车辆图片
//    private Bitmap carScaleBitmap;//绘制车辆缩放图片
    private String TAG = "dove_imgc";
    private int mViewWidth; //宽度
    private int mViewHight; //高度
    private float point_x;//触摸x点
    private float point_y;//触摸y点
    private float point_e = 8;//触点误差值
    private Paint imgPaint;
    private Paint textPaint;
    private Point select_p;

//    private Matrix matrix;
//    private Point center;
//    private Point bmpCenter;
//    private RectF oval;
    private Rect rect;
    private Rect rect_draw;

    private Context mContext;
    private PopupWindow mPop;
    private View mPopView;
    private List<DrawPoint> points = new ArrayList<>();

    public CarBaseView(Context context) {
        super(context);
        init(context);
    }

    public CarBaseView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CarBaseView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CarBaseView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        int widthMode = MeasureSpec.getMode(widthMeasureSpec);   //获取宽的模式
//        int heightMode = MeasureSpec.getMode(heightMeasureSpec); //获取高的模式
//        int widthSize = MeasureSpec.getSize(widthMeasureSpec);   //获取宽的尺寸
//        int heightSize = MeasureSpec.getSize(heightMeasureSpec); //获取高的尺寸
//        LogUtils.i(TAG, "宽的模式:"+widthMode);
//        LogUtils.i(TAG, "高的模式:"+heightMode);
//        LogUtils.i(TAG, "宽的尺寸:"+widthSize);
//        LogUtils.i(TAG, "高的尺寸:"+heightSize);
//        int width;
//        int height ;
//        if (widthMode == MeasureSpec.EXACTLY) {
//            //如果match_parent或者具体的值，直接赋值
//            width = widthSize;
//        } else {
//            //如果是wrap_content，我们要得到控件需要多大的尺寸
//            float imgWidth = carScaleBitmap.getWidth();   //文本的宽度
//            //控件的宽度就是文本的宽度加上两边的内边距。内边距就是padding值，在构造方法执行完就被赋值
//            width = (int) (getPaddingLeft() + textWidth + getPaddingRight());
//            LogUtils.i(TAG, "文本的宽度:"+textWidth + "控件的宽度："+width);
//        }
//        //高度跟宽度处理方式一样
//        if (heightMode == MeasureSpec.EXACTLY) {
//            height = heightSize;
//        } else {
//            float imgHeight = carScaleBitmap.getHeight();
//            height = (int) (getPaddingTop() + textHeight + getPaddingBottom());
//            LogUtils.i(TAG, "文本的高度:"+textHeight + "控件的高度："+height);
//        }
        //保存测量宽度和测量高度
        setMeasuredDimension(carBitmap.getWidth(), carBitmap.getHeight());
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        LogUtils.i(TAG,"w-"+w+"-h-"+h);
        LogUtils.i(TAG,"wo-"+oldw+"-ho-"+oldh);
        mViewWidth = w;
        mViewHight = h;

        //图片拉伸
//        matrix = new Matrix();
//        int bw = carBitmap.getWidth();
//        int bh = carBitmap.getHeight();
//        float scale = Math.min(1f * mViewWidth / bw, 1f * mViewHight / bh);
//        carScaleBitmap = scaleBitmap(carBitmap, scale);
//        int bbw = carScaleBitmap.getWidth();
//        int bbh = carScaleBitmap.getHeight();
//        center = new Point(mViewWidth / 2, mViewHight / 2);
//        LogUtils.i(TAG,"center-"+mViewWidth / 2+"--"+mViewHight / 2);
//        bmpCenter = new Point(bbw / 2, bbh / 2);
//        LogUtils.i(TAG,"bmpCenter-"+bbw / 2+"--"+bbh / 2);
////        matrix.postScale(0.9f, 0.9f, center.x, center.y); // 中心点参数是有用的
////        matrix.postScale(0.9f, 0.9f, center.x - bmpCenter.x, center.x - bmpCenter.x);
//        matrix.postTranslate(center.x - bmpCenter.x, center.y - bmpCenter.y); // 移动到当前view 的中心
////        matrix.postTranslate(center.x, center.y); // 移动到当前view 的中心
//        float left = center.x - bbw / 2;
//        float top = center.y - bbh / 2;
//        float right = center.x + bbw / 2;
//        float bottom = center.y + bbh / 2;
//        oval = new RectF(left, top, right, bottom);
//        LogUtils.i(TAG,"l-"+left+"-t-"+top+"-r-"+right+"-b-"+bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//        canvas.drawBitmap(carScaleBitmap, matrix, imgPaint);
//        rect = new Rect(0, 0,mViewWidth,mViewHight);
        int left_margin = mViewWidth - carBitmap.getWidth();
        int left = left_margin/2;
        int right = carBitmap.getWidth()+left_margin;
        int bottom = carBitmap.getHeight();
        rect = new Rect(left, 0,right,bottom);
        int point_e_int = (int) point_e;
        rect_draw = new Rect(left+point_e_int, 0+point_e_int,
                right-point_e_int,bottom-point_e_int);
        canvas.drawBitmap(carBitmap, rect, rect, imgPaint);
        if(select_p!=null){
            canvas.drawCircle(point_x, point_y, point_e, textPaint);
            showPopSelectUtils();
        }
        drawCarError(canvas);
//        int[] position = new int[2];
//        getLocationInWindow(position);
//        LogUtils.i(TAG,"position-"+position[0]+"-"+position[1]);
//        canvas.drawText("绘制图片", position[0]+15, position[1]+15, textPaint);
    }

    /**
     * 绘制车辆错误信息
     */
    private void drawCarError(Canvas canvas) {
        try{
            for (int i = 0;i < points.size(); i++){
                DrawPoint dp = points.get(i);
                Point p = dp.point;
                canvas.drawText("—", p.x, p.y, textPaint);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 显示绘制工具栏
     */
    private TextView tv_error_line;
    private void showPopSelectUtils() {
        if(mPop==null||mPopView==null){
            mPop = new PopupWindow();
            mPopView = LayoutInflater.from(mContext).inflate(R.layout.custom_car_error, null);
            mPop.setContentView(mPopView);
            mPop.setOutsideTouchable(true);
//            mPop.setTouchable(true);
//            mPop.setFocusable(true);
            mPop.setBackgroundDrawable(new ColorDrawable());
            mPop.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
            mPop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            tv_error_line = mPopView.findViewById(R.id.tv_error_line);
            tv_error_line.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(select_p!=null){
                        points.add(new DrawPoint(select_p,2));
                        select_p = null;
                    }
                    if(mPop!=null){
                        mPop.dismiss();
                    }
                    invalidate();
                }
            });
        }
        if(mPop.isShowing()){
            mPop.dismiss();
        }
        LogUtils.i(TAG,"showAsDropDown--x"+point_x+"-y"+point_y);
        mPop.showAsDropDown(this,(int)point_x+(int)point_e/2,
                (int)point_y+(int)point_e/2-mViewHight);
//        mPop.showAtLocation(this, Gravity.RIGHT,0, 0);
    }

    /*
     * 触摸事件为了确定点击位置的数字
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                select_p = null;
                point_x = event.getX();
                point_y = event.getY();
                LogUtils.i(TAG,"onTouchEvent--x-"+point_x);
                LogUtils.i(TAG,"onTouchEvent--y-"+point_y);
                break;
            case MotionEvent.ACTION_UP:
                if(Math.abs(point_x-event.getX())>point_e
                        || Math.abs(point_y-event.getY())>point_e){
                    LogUtils.i(TAG,"onTouchEvent-2-x-"+event.getX());
                    LogUtils.i(TAG,"onTouchEvent-2-y-"+event.getY());
                    return true;
                }
                if(!rect_draw.contains((int)point_x,(int)point_y)){
                    LogUtils.i(TAG,"onTouchEvent-contains-----");
                    return true;
                }
                try {
                    int pixel = carBitmap.getPixel((int)point_x,(int)point_y);
                    LogUtils.i(TAG,"onTouchEvent-1-pixel-"+pixel);
                    if(0==pixel){
                        return true;
                    }
                    select_p = new Point((int)point_x,(int)point_y);
                }catch (Exception e){
                    e.printStackTrace();
                }
                LogUtils.i(TAG,"onTouchEvent-1-x-"+event.getX());
                LogUtils.i(TAG,"onTouchEvent-1-y-"+event.getY());
                invalidate();
                break;
        }
        return true;
    }

    /**
     * 初始化
     * @param context
     */
    private void init(Context context) {
        mContext = context;

        imgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        imgPaint.setStyle(Paint.Style.FILL);
        imgPaint.setColor(Color.parseColor("#ffffff"));

        textPaint = new Paint();
        textPaint.setColor(Color.parseColor("#000000"));
        textPaint.setTextSize(50);

        carBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.carimg);
    }

//    /**
//     * 根据给定的宽和高进行拉伸
//     * @param origin 原图
//     * @param scale  缩放比例
//     * @return new Bitmap
//     */
//    private Bitmap scaleBitmap(Bitmap origin, float scale) {
//        if (origin == null) {
//            return null;
//        }
//        int height = origin.getHeight();
//        int width = origin.getWidth();
//        Matrix mmatrix = new Matrix();
//        mmatrix.postScale(scale, scale);// 使用后乘
//        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, mmatrix, false);
//        if (!origin.isRecycled()) {
//            origin.recycle();
//        }
//        return newBM;
//    }

    private class DrawPoint{
        public Point point;
        public int type;

        public DrawPoint(Point point, int type) {
            this.point = point;
            this.type = type;
        }
    }

}
